<template>
    <div class="usercenter">
      <classify></classify>

      <div class="login" v-show="login">
        <a href="/#/login">还未登录，请先登录！</a>
      </div>

      <div class="code" v-show="showcode">
        <p v-show="warn" class="warn">{{this.warnmess}}</p>
        <div class="maincode">
          <p>原密码：<input type="password" v-model="oldpassword" @click="input()"></p>
          <p>新密码：<input type="password" v-model="password" @click="input()"></p>
          <p>确认密码：<input type="password" v-model="repassword" @click="input()"></p>
          <span class="sure" @click="cancel()"><a href="###">取消</a></span>
          <span class="sure" @click="modified()"><a href="###">确认</a></span>
        </div>
      </div>

      <div class="material" v-show="main">

        <div class="foundation">

            <div class="photo">
              <img :src="this.list.photo" alt="">
              
              <p v-show="photo"><input type="file" ref="photo" accept="image/*" multiple></p>
              <p v-show="mod"><a href="###" @click="modphoto()">修改头像</a></p>
              <p v-show="photo"><a href="###" @click="upload()">上传头像</a></p>
            </div>
            <div class="foundmater">
              <p>用户名：<i v-show="first">{{this.list.name}}</i>
                <input type="text" v-show="show" v-model="user" name="name"  :placeholder="this.list.name">
              </p>
              <p>
                <span>关注：{{this.list.attention}}</span>
                <span>粉丝：{{this.list.fans}}</span>
                <span>博客：{{this.list.blogs}}</span>
                <span>上传视频：{{this.list.videos}}</span>
                <span>上传书籍：{{this.list.books}}</span>
              </p>
              
              <p>入驻时间：{{this.time}}</p>
            </div>
        
        </div>

        <p class="change"><a href="###" @click="change()">修改资料</a></p>
        <p class="change"><a href="###" @click="code()">修改密码</a></p>

        <div class="more">
          <p>邮箱：{{this.list.email}}</p>
          <p>性别：
            <i v-show="first">{{this.list.gender}}</i>
            <span v-show="show">
              <input type="radio" name="sex" v-model="gender0" class="input man">男
              <input type="radio" name="sex" v-model="gender1" class="input woman">女
            </span>
          </p>
          
          <p>生日：
            <i v-show="first">{{this.day}}</i>
            <input type="date" v-show="show" v-model="birthday" name="birthday">
          </p>
          
          <p>学校：
            
            <i v-show="first">{{this.list.education}}</i>
            <input type="text" v-show="show" v-model="education" :placeholder="this.list.education" name="education">
          </p>
          <p>个性签名：
            
            <i v-show="first">{{this.list.motto}}</i>
            <input type="text" v-show="show" v-model="motto" :placeholder="this.list.motto" name="motto">
          </p>
          <p>个人简介：
            
            <i v-show="first">{{this.list.introduction}}</i>
            <input type="text" v-show="show" v-model="introduction" :placeholder="this.list.introduction" name="introduction">
          </p>
          <span class="yes" v-show="show" @click="back()"><a href="###">取消</a></span>
          <span class="yes" v-show="show" @click="sure()"><a href="###">确定</a></span>
          
        </div>
      </div>

    </div>
</template>

<script>
// input默认值问题，需默认未修改之前的值
import qs from 'qs'
import axios from 'axios'
import classify from './classify'
export default {
    name: 'usercenter',
    components: {
      classify,
    },
    data () {
      return {
        list: [],
        time: '',
        day: '',
        first: true,
        show: false,
        login: true,
        main: false,
        wu: true,
        no: true,
        showcode: false,
        warn: false,
        photo: false,
        mod: true,
       
        user: '',
        gender: '',
        gender0: '',
        gender1: '',
        birthday: '',
        education: '',
        motto: '',
        introduction: '',
        photourl: '../../../../../static/imgs/photo.jpeg',

        warnmess: '',
        oldpassword: '',
        password: '',
        repassword: '',

        newphoto: '',
        photoname: '',

      }
    },

    methods: {
      modphoto () {
        this.photo = true
        this.mod = false
      },

      getBase64 (file) {
        return new Promise(function (resolve, reject) {
          let reader = new FileReader()
          let imgResult = ''
          reader.readAsDataURL(file)
          reader.onload = function () {
            imgResult = reader.result
          }
          reader.onerror = function (error) {
            reject(error)
          }
          reader.onloadend = function () {
            resolve(imgResult)
          }
        })
      },

      dataURItoBlob (dataURI) {
        // base64 解码
        // console.log('dataURI', dataURI)
        let byteString = window.atob(dataURI.split(',')[1])
        let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
        // let T = mimeString.split('/')[1]
        let ab = new ArrayBuffer(byteString.length)
        let ia = new Uint8Array(ab)
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i)
        }
        return new Blob([ab], {type: mimeString})
      },


      upload () {
        // this.photoname = this.$refs.photo.value
        // console.log(this.photoname)
        let data = this.$refs.photo.files[0]
        console.log('data', data)
        this.photoname = data.name
        // console.log(this.photoname)
        // console.log(this.getBase64(data))
        this.getBase64(data).then(res => {
          // this.newphoto = res
          // console.log('this.newphoto', this.newphoto)
          this.newphoto = this.dataURItoBlob(res)
          // console.log('newphoto', this.newphoto)
          if (this.newphoto !== '') {
            this.photo = false
            this.mod = true
          
            // 获取修改后的图片url
            // this.photourl = this.$refs.photo.value
            // console.log(this.photourl)

            // console.log(this.newphoto)

            var formdata = new FormData()
            formdata.append('photo', this.newphoto)
            console.log(formdata)
            // formdata.append('photo', ' '+this.photoname)

            // console.log(formdata.has('photo'))

            // console.log(formdata.get("photo"))

            // let postData = qs.stringify({
            //     photo: formdata,
            //     img: this.photoname,
            // })

            // console.log(postData)
            
            axios.post(`/api/user/updatePhoto`, formdata, {headers:{'Content-type': 'multipart/form-data'}}).then((response) => {

              if (response.status === 200) {
                this.$message({
                  type: 'success',
                  message: response.data
                })

                axios.post(`/api/user/getUser`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                  if (response.status === 200) {
                    if (response.data !== '') {
                      this.main = true
                      this.login = false
                    }
                    this.list = response.data
                    this.time = this.list.createtime.slice(0,10)
                    if (this.list.birthday != "") {
                      this.day = this.list.birthday.slice(0,10)
                    }
                    if(this.list.gender == "1") {
                      this.list.gender = "男"
                    } else {
                      this.list.gender = "女"
                    }
                    // console.log(this.list.birthday)

                  } 

                })
                
              } 

            })
          }
          else {
            this.$message({
              type: 'error',
              message: "请先选择文件！"
            })
          }
        })
        // console.log('this.newphoto', this.newphoto)
        
      },

      change () {
        this.first = false
        this.show = true
        if (this.list.gender == "女") {
          document.getElementsByClassName('woman')[0].setAttribute('id','sex')
        } else {
          document.getElementsByClassName('man')[0].setAttribute('id','sex')
        }
        document.getElementById('sex').checked = true
      },

      back () {
        this.show = false
        this.first = true
      },

      sure () {
        this.show = false
        

        if(this.gender0 != "") {
          this.gender = 1
        } else {
          this.gender = 0
        }
        console.log(this.gender0)
        console.log(this.gender)


        if (this.user == '') {
          this.user = this.list.name
        }
        
        if (this.birthday == '') {
          this.birthday = this.day
        }

        let postData = qs.stringify({
          username: this.user,
          gender: this.gender,
          birthday: this.birthday,
          education: this.education,
          motto: this.motto,
          introduction: this.introduction,
        })

        axios.post(`/api/user/updateInfo`, postData, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

          if (response.status === 200) {
              // console.log(response.data)
              // console.log(this.list.name)
          } 
        })

        axios.post(`/api/user/getUser`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

          if (response.status === 200) {
            if (response.data !== '') {
              this.main = true
              this.login = false
            }
            this.list = response.data
            this.time = this.list.createtime.slice(0,10)
            if (this.list.birthday != "") {
              this.day = this.list.birthday.slice(0,10)
              // console.log(this.day)
            }
            if(this.list.gender == 1) {
              this.list.gender = "男"
            } else {
              this.list.gender = "女"
            }
            // console.log(this.list)
            // console.log(this.list.birthday)
          } 

        })

        this.first = true
        this.$router.go(-1)
      },

      code () {
        this.showcode = true
      },

      cancel () {
        this.showcode = false
      },

      modified () {
        let postData = qs.stringify({
          oldPassword: this.oldpassword,
          password: this.password,
          repassword: this.repassword,
        })

        axios.post(`/api/user/updatePassword`, postData, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

          if (response.status === 200) {
            this.warn = true
            console.log(response.data)
            this.warnmess = response.data
            if (response.data === "修改成功") {

              this.showcode = false
            }
          } 

        }) 
        
      },

      input () {
        this.warn = false
      },

    },

    

    created () {
      axios.post(`/api/user/getUser`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

        if (response.status === 200) {
          if (response.data !== '') {
            this.main = true
            this.login = false
          }
          this.list = response.data
          console.log(this.list)
          this.time = this.list.createtime.slice(0,10)
          if (this.list.birthday != "") {
            this.day = this.list.birthday.slice(0,10)
          }
          if(this.list.gender == "1") {
            this.list.gender = "男"
          } else {
            this.list.gender = "女"
          }
          // console.log(this.list.birthday)

        } 

      }) 

    },
// input框自动获取焦点失败
    // mounted () {
    //   this.$nextTick(() =>{
    //     this.$refs.name.focus()
    //   })
    // },
}
</script>

<style lang="stylus" scoped>
.usercenter
  width 100%
  height auto
  position relative
  // background-color #fff
  .login
    width 80%
    line-height 36.5rem
    top 0
    margin-left 17%
    margin-bottom 2rem
    text-align center
    font-size 1rem
    position absolute
    border 1px #ccc solid
    border-radius 10px
    box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
    background-color #fff
    a
      color red
    a:hover
      color #26a2ff
  .code
    width 20%
    height 14rem
    position absolute 
    top 16rem
    left 30%
    z-index 1
    border 1px #ccc solid
    border-radius 10px
    box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
    background-color #fff
    .warn 
      line-height 1rem
      color #26a2ff
      margin-top .5rem
      text-align center
      position relative
    .maincode
      width 100%
      height 10rem
      position absolute 
      top 2rem
      p
      line-height 3rem
      margin-left 3%
      // background-color red
      input 
        width 70%
        border 1px #ccc solid
        text-indent .5rem
    .sure
      padding .5rem 1rem
      line-height 2rem
      text-align center
      border 1px #ccc solid
      border-radius 10px
      margin-left 20%
      // background-color red
      a
        color #26a2ff
    .sure:hover
      background-color skyblue
      a
        color #fff
  .material
    width 80%
    height auto
    top 0
    margin-left 17%
    margin-bottom 2rem
    position absolute
    border 1px #ccc solid
    border-radius 10px
    box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
    background-color #fff 
    input
      width 20%
    .foundation
      height auto
      padding 1rem
      border-bottom .05rem #ccc solid
      // background-color red
      .photo
        height 6rem
        margin-left 3rem
        margin-top 1.5rem
        position absolute
        // background-color red
        img 
          height 5rem
          width 5rem
          margin-left .5rem
          border-radius 50%
          border .05rem #ccc solid
          box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
        p 
          width 10rem
          line-height 1rem
          text-align center
          margin-top 1rem 
          font-size .8rem
          margin-left -2rem
          // background-color red
          input
            width 100%
          a
            color #26a2ff
      .foundmater
        width 80%
        margin-left 18%
        // background-color skyblue
        p
          line-height 4rem
          font-size .9rem
          // background-color red
          input 
            border .05rem #333 solid
            text-indent .5rem
            font-size .8rem
          span 
            margin-right 5%
    .change 
        margin-left 5.4rem
        margin-top 2rem
        font-size .8rem
        a
          color #26a2ff
    .more
      width 100%
      height auto
      margin-top -6.3rem
      padding-bottom  .7rem
      // background-color red
      p
        line-height 4rem
        margin-left 14.6rem
        font-size .9rem
        input 
          border .05rem #333 solid
          text-indent .5rem
          font-size .8rem
        .input 
          width 3%
      .yes
        width 5%
        padding .5rem 1rem
        text-align center
        margin-left 14.6rem
        border-radius .5rem
        border .05rem #ccc solid
        background-color #fff
        a
          color #26a2ff
      .yes:hover
        background-color skyblue
        a
          color #fff
</style>